<template>
	<!-- <view>
		<icon v-if="currentId === item.id" type="success_no_circle" size="14"></icon>
	</view> -->
	<up-skeleton rows="6" :loading="loading" :title="false">
		<u-empty v-if="noShop" mode="search" text="请扫描充电设备的二维码"></u-empty>
		<view v-else class="layout">
			<view class="title">
				<text>选择充电时长</text>
			</view>
			<scroll-view class="wrapper">
				<up-cell-group>
					<up-cell v-for="(item, index) in list" :key="index" @click="itemChange(item.id)">
						<template #title>
							<text>{{ item.duration }}分钟</text>
						</template>
						<template #right-icon v-if="currentId === item.id">
							<icon type="success_no_circle" size="14"></icon>
						</template>
					</up-cell>
				</up-cell-group>
			</scroll-view>
			<view class="footer">
				<button type="primary" :loading="submitLoading" @click="handleCharge">
					立即支付，¥{{ currentPrice }}元
				</button>
				<up-safe-bottom></up-safe-bottom>
			</view>
		</view>
	</up-skeleton>
</template>


<script setup>
	import api from '@/api/app.js'
	import useAppStore from '@/store/app.js'
	import {
		getQueryString,
	} from '@/common/utils/index.js'

	const appStore = useAppStore()
	const loading = ref(true)
	const submitLoading = ref(false)
	const noShop = ref(false)
	const shopId = ref()
	const list = ref([])
	const orderNumber = ref('')
	const currentId = ref(null)
	const currentPrice = computed(() => {
		const item = list.value.find(item => item.id === currentId.value)
		return item ? item.price : ''
	})

	// 切换选项
	function itemChange(id) {
		currentId.value = id
		orderNumber.value = ''
	}

	function getDataList() {
		loading.value = true
		const params = {
			shop_id: shopId.value
		}
		return api.getDataList(params).then(res => {
			list.value = res.data.data
		}).finally(() => {
			setTimeout(() => {
				loading.value = false
			}, 2000)
		})
	}

	function routerToBusiness() {
		uni.navigateTo({
			url: '/pages/businessIndex/businessIndex'
		})
	}

	function handleCharge() {
		if (!appStore.isLogin) {
			appStore.login().then(() => {
				createOrder()
			})
		} else {
			createOrder()
		}
	}

	function createOrder() {
		if (submitLoading.value) {
			return
		}

		if (orderNumber.value) {
			createWxPreOrder(orderNumber.value)
			return;
		}
		submitLoading.value = true
		api.createOrder({
			shop_id: shopId.value,
			goods_id: currentId.value,
		}, {
			showLoading: true,
		}).then(res => {
			const orderNum = res.data.data.order_num
			orderNumber.value = orderNum
			orderNum && createWxPreOrder(orderNum)
			// uni.navigateTo({
			//     url: `/pages/result/result?type=success&orderNum=${orderNum}`
			// })
		}).catch(() => {
			submitLoading.value = false
		})
	}

	function createWxPreOrder(order_number = '') {
		api.wxPayOrder({
			order_number
		}).then(res => {
			const data = JSON.parse(res.data.data)
			const {
				timeStamp,
				nonceStr,
				paySign
			} = data;

			const payParams = {
				provider: 'wxpay',
				orderInfo: data,
				timeStamp,
				nonceStr,
				package: data.package,
				signType: 'MD5',
				paySign,
				success: e => {
					console.log('支付成功')
					checkOrder()
				},
				fail: err => {
					if (err.errMsg.indexOf('取消') > -1 || err.errMsg.indexOf('cancel') > 1 || err
						.errMsg.indexOf('-2') > -1) {
						uni.showToast({
							icon: 'none',
							title: '取消支付'
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: '支付遇到错误，请稍候重试'
						})
						console.log(err);
					}
				},
				complete: () => {
					submitLoading.value = false
				}
			};
			console.log(payParams);
			uni.requestPayment(payParams);
		})
	}

	function orderDetail() {
		return api.orderDetail({
			order_number: orderNumber.value
		})
	}

	// 轮询次数
	const orderCheckTime = ref(5)
	const orderCheckTimer = ref(null)
	async function checkOrder() {
		uni.showLoading({
			title: '支付中...'
		})
		orderCheckTime.value = 5
		orderCheckTimer.value = setInterval(async () => {
			const res = await orderDetail()
			if (res.data.data.pay_status === "1") {
				uni.hideLoading()
				clearInterval(orderCheckTimer.value)
				orderNumber.value = ''
				uni.navigateTo({
					url: `/pages/result/result?type=success&msg=支付成功`
				})
			} else if (res.data.data.pay_status === "-1") {
				uni.hideLoading()
				clearInterval(orderCheckTimer.value)
				uni.showToast({
					icon: 'none',
					title: '支付已取消'
				})
			} else {
				orderCheckTime.value--
				if (orderCheckTime.value <= 0) {
					uni.hideLoading()
					clearInterval(orderCheckTimer.value)
					orderNumber.value = ''
					uni.navigateTo({
						url: `/pages/result/result?type=warn&msg=支付失败，请重新购买`
					})
				}
			}
		}, 1000)
	}

	onLoad(async (query) => {
		let id = '9' // 给个默认id，避免审核小程序的时候无数据
		if (query.q) {
			if (query.q.includes('redirect')) {
				const redirect = getQueryString(query.q, 'redirect')
				let url = 'pages/index/index'
				if (redirect === 'bindex') {
					url = '/pages/bindex/bindex'
				}
				uni.redirectTo({
					url,
				})
				return;
			} else if (query.q.includes('shop_id')) {
				id = getQueryString(query.q, 'shop_id')
			}
		} else if (query.shop_id) {
			id = query.shop_id
		}

		shopId.value = id
		if (shopId.value) {
			await getDataList()
			currentId.value = list.value[0].id
		}else {
			noShop.value = true
			loading.value = false
		}
	})
	onMounted(async () => {

	})
</script>

<style lang="scss">
	.layout {
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.title {
		padding: 32px 0;
		font-size: 22px;
		color: #181818;
		margin-bottom: 16px;
		text-align: center;
		font-weight: 500;

		>text {
			font-size: $uni-font-size-lg;
			color: $uni-color-title;
		}
	}

	.wrapper {
		padding: 0 16px 16px;
		margin-bottom: 16px;
		min-height: 60vh;
		color: #333;
	}

	.footer {
		width: 60%;
		margin: 0 auto;
	}



	.list {
		&-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 56px;
			padding: 0 16px;
			margin-bottom: 16px;
			font-size: $uni-font-size-lg;
			border: 1px solid $uni-border-color;
			border-radius: $uni-border-radius-base;

			&.is-active {
				color: $uni-color-primary;
				// color: #fff;
				border-color: $uni-color-primary;
				// background-color: $uni-color-primary;
			}

			.minutes {
				margin: 0 4px;
				font-weight: bold;
				font-size: 1.2em;
				color: red;
			}
		}
	}
</style>